package com.lichongbing.lyoggl.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lichongbing.lyoggl.model.Project;
import com.lichongbing.lyoggl.service.LyogglUsersService;
import com.lichongbing.lyoggl.service.ProjectService;
import com.lichongbing.lyoggl.service.SubscriptionService;
import com.lichongbing.lyoggl.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2022/4/7 2:31 下午
 * @description: TODO
 */
@Slf4j
@RestController
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private SubscriptionService subscriptionService;
    @Autowired
    private LyogglUsersService lyogglUsersService;

    /**
     * 新增项目
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping("/create")
    public JSONObject createProject(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        String token = request.getHeader("token");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        String storeid =  jsonObject.getString("storeid");
        String userid = JwtTokenUtils.getUserid(token);
        int rows = projectService.findRowsByUid(userid);
        String expirationdate = "2022-09-25 01:00:00";
        String subscriptions = subscriptionService.getSubscriptions(userid, storeid);
        if (subscriptions!=null){
            expirationdate = subscriptions;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date parses = simpleDateFormat.parse(expirationdate);
            long expirations = parses.getTime();

        long nowtime = System.currentTimeMillis();

        Project project = new Project();

         String id = UUID.randomUUID().toString().replace("-", "");
        if(expiration==false){
            if((nowtime <= expirations) || (rows <= 200)){
                project.setId(id);
                project.setName(jsonObject.getString("name"));
                project.setUid(userid);
                jsonObject.put("code", 200);
                jsonObject.put("msg", "添加成功");
                projectService.save(project);
                return jsonObject;
            }else {
                jsonObject.put("code", 201);
                jsonObject.put("msg", "服务到期需要订阅升级");
                return jsonObject;
            }
        }else {
            jsonObject.put("code", 401);
            jsonObject.put("msg", "token失效");
            return jsonObject;
        }
        }catch (Exception e){
            System.out.println(e.getMessage());
            jsonObject.put("code", 409);
            jsonObject.put("msg", e.getMessage());
            return jsonObject;
        }
    }

    /**
     * 根据用户id查询项目
     * @param request
     * @return
     */
    @PostMapping("/findByUid")
    public JSONObject findByUid( HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        String token = request.getHeader("token");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        if(expiration==false){
            String userid = JwtTokenUtils.getUserid(token);
            boolean flag = lyogglUsersService.isToken(userid);
            if(flag) {
            jsonObject.put("code",200);
            jsonObject.put("msg","查询成功");
            jsonObject.put("data",projectService.findByUid(userid));
            return jsonObject;}else {
                jsonObject.put("code",402);
                jsonObject.put("msg","token无效");
                return jsonObject;
            }
        }else {
            jsonObject.put("code",400);
            jsonObject.put("msg","token过期");
            return jsonObject;
        }
    }

    /**
     * 根据用户id删除项目
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/delete/{id}")
    public JSONObject delete(@PathVariable String id, HttpServletRequest request){
        JSONObject jsonObject = new JSONObject();
        String token = request.getHeader("token");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        if(expiration==false){
            String userid = JwtTokenUtils.getUserid(token);
            projectService.deleteByUid(id,userid);
            jsonObject.put("code",200);
            jsonObject.put("msg","删除成功");
            return jsonObject;
        }else {
            jsonObject.put("code",400);
            jsonObject.put("msg","token过期");
            return jsonObject;
        }
    }

    /**
     * 根据用户id更新项目
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping("/update")
    public JSONObject update(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        JSONObject jsonObject1 = new JSONObject();
        String token = request.getHeader("token");
        String name = jsonObject.getString("name");
        String content = jsonObject.getString("content");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        if(expiration==false){
            if (!name.equals("") && !content.equals("")){
                projectService.update(null, Wrappers.<Project>lambdaUpdate().set(Project::getName,name).set(Project::getContent,content).eq(Project::getId,jsonObject.getString("id")));
            }else if (!name.equals("") && content.equals("")){
                projectService.update(null, Wrappers.<Project>lambdaUpdate().set(Project::getName,name).eq(Project::getId,jsonObject.getString("id")));

            }else if (name.equals("") && !content.equals("")){
              projectService.update(null, Wrappers.<Project>lambdaUpdate().set(Project::getContent,content).eq(Project::getId,jsonObject.getString("id")));
            }

            jsonObject1.put("code",200);
            jsonObject1.put("msg","更新成功");
            return jsonObject1;
        }else {
            jsonObject1.put("code",400);
            jsonObject1.put("msg","token过期");
            return jsonObject1;
        }
    }

}
